import type { Model } from '@/models/connect';
import type { InitialState } from './types';
import { namespace } from './types';
import { queryXBOMListAPI, createXbomAPI, getXbomApi, doReceiveOrderById, findByBasicPno18 } from './services';

// xbom数据
const initialState: InitialState = {
  list: [] as any, // 列表数据
  searchParams: {} as any, // 列表查询参数
  selectedRows: [], // 列表选中的行
  xbomDetailVisible: false, // 详情弹窗状态
  xbomData: {}, // xbom对象数据
  recipientListVisible: false,
  defaultPeopleSetListVisible: false,
};

export default {
  namespace,
  state: initialState,
  effects: {
    // 搜索接口
    *query({ payload }, { put, call }) {
      try {
        const params = {
          pageInfo: { beginIndex: 0, pageSize: 50 },
          filterInfo: {
            sortOrder: 'asc',
            ...payload,
          },
        };
        const res = yield call(queryXBOMListAPI, params);
        const content = res?.content || [];
        yield put({
          type: 'save',
          payload: {
            searchParams: payload,
            list: content,
          },
        });
      } catch (error) {}
    },
    // 复制功能 -- 可选中的特改订单列表
    *querySlectOrders({ payload }, { put, call }) {
      try {
        const params = {
          orderId: payload?.orderId,
          basicPno18: payload?.basicPno18,
        };
        const content = yield call(findByBasicPno18, params);
        yield put({
          type: 'save',
          payload: {
            list: content,
          },
        });
      } catch (error) {}
    },
    *queryXbom({}: any, { call, put, select }: any) {
      const { selectedRows } = yield select((state) => state[namespace]);
      if (!selectedRows[0]?.xbomId) {
        return;
      }
      const xbomRes = yield call(getXbomApi, {
        xbomId: selectedRows[0].xbomId,
      });
      yield put({
        type: 'save',
        payload: {
          xbomData: xbomRes,
        },
      });
    },
    *createXbom({ payload }: any, { call, put }: any) {
      const xbomRes = yield call(createXbomAPI, payload);
      yield put({
        type: 'save',
        payload: {
          xbomData: xbomRes,
        },
      });
    },
    *receiveOrderEffect({}: any, { call, select }: any) {
      const { selectedRows } = yield select((state) => state[namespace]);
      if (!selectedRows.length) {
        return;
      }
      yield call(doReceiveOrderById, { id: selectedRows[0].id });
    },
  },
  reducers: {
    // 保存全局对象
    save(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
} as Model<{
  [namespace]: Readonly<typeof InitialState>;
}>;
